package com.tee.live.im.router.provider.cluster;

import org.apache.dubbo.rpc.*;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;

import java.util.List;

/**
 * @author tee
 * @date 2025/11/10
 */
public class ImRouterClusterInvoker<T> extends AbstractClusterInvoker<T> {

        public ImRouterClusterInvoker(Directory<T> directory) {
            super(directory);
        }

    @Override
    protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
        checkWhetherDestroyed();
        String ip = (String) RpcContext.getContext().get("ip");
        if (ip == null) {
            throw new RuntimeException("ip can not be null");
        }
        // 获取到指定的rpc服务提供者的所有地址信息
        Invoker<T> matchInvoker = invokers.stream().filter(invoker -> {
            String serverIp = invoker.getUrl().getHost() + ":" + invoker.getUrl().getPort();
            return serverIp.equals(ip);
        }).findFirst().orElse(null);

        if (matchInvoker == null) {
            throw new RuntimeException("非法ip,当前ip:" + ip);
        }

        return matchInvoker.invoke(invocation);
    }
}
